<template>
  <div>
    <div ref="echartDom" style="width: 100%; height: 100%"></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watchEffect, shallowRef, inject } from "vue";
import china from "@/utils/china.json";
import { pxToRem } from "@/utils/index";
const chinaGeoCoordMap = ref();
const chinaDatas = ref();

const myChart = shallowRef(null);
const echartDom = ref(null);
const echarts = inject("echarts");
let mapData = china;
echarts.registerMap("china", mapData);

// 接收参数
const props = defineProps({
  housingSupplyStatsData: {
    type: Object,
    default: () => {},
  },
});
const emits = defineEmits(["mapNameChange"]);

const getEchart = () => {
  var newData1 = [
    {
      name: "北京",
      value: 0,
    },
    {
      name: "天津",
      value: 0,
    },
    {
      name: "河北",
      value: 0,
    },
    {
      name: "山西",
      value: 0,
    },
    {
      name: "内蒙古",
      value: 0,
    },
    {
      name: "辽宁",
      value: 0,
    },
    {
      name: "吉林",
      value: 0,
    },
    {
      name: "黑龙江",
      value: 0,
    },
    {
      name: "上海",
      value: 0,
    },
    {
      name: "江苏",
      value: 0,
    },
    {
      name: "浙江",
      value: 0,
    },
    {
      name: "安徽",
      value: 0,
    },
    {
      name: "福建",
      value: 0,
    },
    {
      name: "江西",
      value: 0,
    },
    {
      name: "山东",
      value: 0,
    },
    {
      name: "河南",
      value: 0,
    },
    {
      name: "湖北",
      value: 0,
    },
    {
      name: "湖南",
      value: 0,
    },
    {
      name: "重庆",
      value: 0,
    },
    {
      name: "四川",
      value: 0,
    },
    {
      name: "贵州",
      value: 0,
    },
    {
      name: "云南",
      value: 0,
    },
    {
      name: "西藏",
      value: 0,
    },
    {
      name: "陕西",
      value: 0,
    },
    {
      name: "甘肃",
      value: 0,
    },
    {
      name: "青海",
      value: 0,
    },
    {
      name: "宁夏",
      value: 0,
    },
    {
      name: "新疆",
      value: 0,
    },
    {
      name: "广东",
      value: 0,
    },
    {
      name: "广西",
      value: 0,
    },
    {
      name: "海南",
      value: 0,
    },
    {
      name: "台湾",
      value: 0,
    },
  ];
  chinaGeoCoordMap.value = props.housingSupplyStatsData.lineData.chinaGeoCoordMap;
  chinaDatas.value = props.housingSupplyStatsData.lineData.chinaDataMap;
  var newData = [];
  chinaDatas.value.forEach((item) => {
    newData.push({
      name: item[0].name,
      value: item[0].value,
    });
  });
  try {
    var maxValue = newData.reduce((max, item) => {
      return item.value > max ? item.value : max;
    }, newData[0].value);
  } catch (e) {
    var maxValue = 1000;
  }

  var convertData = function (data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
      var dataItem = data[i];
      var fromCoord = chinaGeoCoordMap.value[dataItem[0].name];
      var toCoord = props.housingSupplyStatsData.lineData.centerPoint.lngLat;
      // Object.keys(obj)[0]
      if (fromCoord && toCoord) {
        res.push({
          fromName: dataItem[0].name,
          toName: props.housingSupplyStatsData.lineData.centerPoint.name,
          coords: [fromCoord, toCoord],
          value: dataItem[0].value,
          visualMap: false,
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "#f00", // 0% 处的颜色
              },
              {
                offset: 1,
                color: "#fff", // 100% 处的颜色
              },
            ],
            global: false, // 缺省为 false
          },
        });
      }
    }
    return res;
  };
  var series = [];
  [["", chinaDatas.value]].forEach(function (item, i) {
    series.push(
      {
        type: "lines",
        zlevel: 2,
        effect: {
          show: true,
          period: 6, //箭头指向速度，值越小速度越快
          // trailLength: 00, //特效尾迹长度[0,1]值越大，尾迹越长重
          symbol: "arrow", //箭头图标
          color: "#FFC352", // 特效颜色
          symbolSize: 4, //图标大小
        },
        lineStyle: {
          normal: {
            width: 1, //尾迹线条宽度
            opacity: 1,
            curveness: 0.3,
            type: "dashed",
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: "#FFC352", // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: "#fff", // 100% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            },
          },
        },
        label: {
          normal: {
            show: false,
            position: "middle",
            formatter: "{b}",
          },
        },
        data: convertData(item[1]),
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        zlevel: 2,
        rippleEffect: {
          //涟漪特效
          color: "#FFC352",
          period: 6, //动画时间，值越小速度越快
          brushType: "fill", //波纹绘制方式 stroke, fill
          scale: 4, //波纹圆环最大限制，值越大波纹越大
        },
        label: {
          normal: {
            show: true,
            position: "bottom", //显示位置
            //offset: [5, 0], //偏移设置
            formatter: "{b}", //圆环显示文字
            textStyle: {
              color: "#fff",
              fontSize: pxToRem(12),
            },
          },
        },
        symbol: "circle",
        symbolSize: 3,
        itemStyle: {
          normal: {
            show: true,
            color: "#E5FC64",
          },
        },
        data: item[1].map(function (dataItem) {
          return {
            name: dataItem[0].name,
            value: undefined == chinaGeoCoordMap.value[dataItem[0].name] ? "" : chinaGeoCoordMap.value[dataItem[0].name].concat([dataItem[0].value]),
            visualMap: false,
          };
        }),
      },
      //被攻击点
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        zlevel: 2,
        rippleEffect: {
          color: "#E5FC64",
          period: 6,
          brushType: "fill",
          scale: 4,
        },
        label: {
          normal: {
            show: true,
            position: "right",
            formatter: "{b}",
            textStyle: {
              color: "#fff",
            },
          },
          emphasis: {
            show: true,
          },
        },
        symbol: "circle",
        symbolSize: 6,
        itemStyle: {
          normal: {
            show: true,
            color: "#f00",
          },
        },
        // data: [
        //   {
        //     name: item[0],
        //     value: chinaGeoCoordMap[item[0]].concat([10]),
        //   },
        // ],
      },
      {
        type: "map",
        map: "china",
        geoIndex: 0,
        aspectScale: 0.75, //长宽比
        showLegendSymbol: false, // 存在legend时显示
        label: {
          normal: {
            show: true,
          },
          emphasis: {
            show: false,
            textStyle: {
              color: "#fff",
            },
          },
        },
        roam: true,
        itemStyle: {
          normal: {
            areaColor: "#031525",
            borderColor: "#3B5077",
          },
          emphasis: {
            areaColor: "#2B91B7",
          },
        },
        animation: false,
        data: newData.length > 0 ? newData : newData1,
      }
    );
  });
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    var option = {
      tooltip: {
        trigger: "item",
        formatter: function (params, ticket, callback) {
          if (params.seriesType == "effectScatter") {
            return params.marker + params.data.name + "" + params.data.value[2];
          } else if (params.seriesType == "lines") {
            return params.data.fromName + " -> " + params.data.toName + "<br />" + params.data.value;
          } else {
            return params.name;
          }
        },
      },
      visualMap: {
        min: 0,
        max: maxValue / 10,
        show: true,
        left: "left",
        text: ["高", "低"], // 文本，默认为数值文本
        calculable: true,
        seriesIndex: [3],
        inRange: {
          color: ["#2073CA", "#5978C3", "#B95E75", "#E55151"], // 蓝绿
        },
        bottom: pxToRem(20),
        orient: "horizontal", // 设置为水平展示
        itemWidth: pxToRem(13),
        itemHeight: pxToRem(160), // 调整高度值
        textStyle: {
          color: "transparent",
        },
      },
      geo: {
        map: "china",
        roam: true, //是否允许缩放
        zoom: 1.2,
        label: {
          emphasis: {
            show: true,
          },
        },
        itemStyle: {
          normal: {
            show: false,
            color: "rgba(48,97,186，0)", //地图背景色
            borderColor: "rgba(0, 0, 0,0)", //省市边界线
          },
          emphasis: {
            show: false,
            color: "#2B91B7", //悬浮背景
          },
        },
      },
      series: series,
    };
    myChart.value.getZr().off("click");
    myChart.value.setOption(option);
  }
};

const updateChart = () => {
  chinaGeoCoordMap.value = props.housingSupplyStatsData.lineData.chinaGeoCoordMap;
  chinaDatas.value = props.housingSupplyStatsData.lineData.chinaDataMap;
  if (myChart.value && !myChart.value.isDisposed()) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  getEchart();
};

defineExpose({
  updateChart,
});

watchEffect(() => {
  updateChart();
});

onMounted(() => {
  getEchart();
  window.addEventListener("resize", updateChart);
});

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
});
</script>
